package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;


    //查询一级分类
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }
    //查询二级分类
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
        .eq("category1_id",category1Id));
    }
    //根据二级分类Id 查询三级分类集合
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",category2Id));
    }

    //根据分类的ID 查询平台属性及属性值集合
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }
    //保存平台属性及属性值
    @Override
    @Transactional//打开事物
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1:平台属性表  1
        baseAttrInfoMapper.insert(baseAttrInfo);//返回主键
        //平台属性值表 多
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.forEach(attrValue ->{
                //设置平台属性的外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
            //手写SQL 性能是非常高
            //insert into base_attr_value

        }
    }
    //品牌分页查询
    @Override
    public IPage<BaseTrademark> baseTrademarkList(Integer page, Integer limit) {
        Page<BaseTrademark> page1 = new Page<>(page, limit);
        return baseTrademarkMapper.selectPage(page1,null);
    }
    //保存品牌
    @Override
    public void baseTrademarkSave(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }
    //商品 分页查询
    @Override
    public IPage<SpuInfo> spuPage(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<SpuInfo>(page,limit),
                new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
    }
    //查询品牌列表
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }
    //查询销售属性列表
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }
    //商品保存
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1.商品表
        spuInfoMapper.insert(spuInfo);
        //图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断集合是否为空 判断长度是否大于0
        if (!CollectionUtils.isEmpty(spuImageList) && spuImageList.size()>0){
            spuImageList.forEach(spuImage -> {
                //外键
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //商品与销售属性关联表
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList) && spuSaleAttrList.size()>0){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                //外键
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                //商品与销售属性值关联表
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                    //销售属性名称
                    spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                    //外键
                    spuSaleAttrValue.setSpuId(spuInfo.getId());
                    spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                });

            });
        }

    }
    //根据id删除品牌
    @Override
    public void removeById(Long id) {
        baseTrademarkMapper.deleteById(id);
    }
    //库存SKu分页查询
    @Override
    public IPage skuPage(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page,limit),null);
    }
    //根据spuId 查询商品的所有图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
        .eq("spu_id",spuId));
    }

    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }
    //保存SKUInfo
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
       // 1、Sku_info   核心表
        skuInfoMapper.insert(skuInfo);
//            |--2、sku_image库存的图片表   某一个颜色的所有图片
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            //外键
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
//                |--3、sku_attr_value 库存的平台属性及属性值表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
//                |--4、sku_sale_attr_value 库存的销售属性及属性值表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            //skuId
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //spuId
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }
    @Autowired
    private RabbitService rabbitService;
    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);//解决 硬编码问题
        skuInfoMapper.updateById(skuInfo);// update sku_info set is_sale = 1 where id = ?
        // 发消息通知搜索微服务 添加商品的索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,skuId);



    }
    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.CANCELSALE);//解决 硬编码问题
        skuInfoMapper.updateById(skuInfo);// update sku_info set is_sale = 0 where id = ?
        // 发消息通知搜索微服务 删除商品索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);


    }

   /* //查库存信息 及库存的图片 条件库存Id
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key
        String cacheKey =  RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;  //本次是查询SkuInfo的数据 拼接了 skuId
        //1:查询缓存
        SkuInfo skuInfo =(SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //2:有 直接返回
        if(skuInfo == null){
            //3:没有 查询DB  挂掉就是宕机
            String cacheLockKey =   RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //UUID 判断是否为自己的锁的唯一标识
            String uuid = UUID.randomUUID().toString();

            //3.1查询DB之前要求枷锁 以防止是热点数据 大量请求 只能通过一个     设置锁的过期时间  后面两个参数
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid,2,TimeUnit.SECONDS);
            if (isLock){
                try {
                    //库存信息
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if(skuInfo != null){
                        //库存的图片
                        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                .eq("sku_id", skuId));
                        skuInfo.setSkuImageList(skuImageList);
                        //4:再保存一份到缓存中
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), //解决缓存雪崩
                                TimeUnit.SECONDS);//过期时间一天+随机数（5分钟之内）
                    }else{
                        //代码能执行在此处  说明DB中也没有数据
                        //缓存的穿透问题  不让访问把DB弄挂掉
                        //将空结果保存到缓存中
                        skuInfo = new SkuInfo();// 不是NULL 是空结果  结果是skuInfo对象 对象中没有数据 叫空结果
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);//过期时间是5分钟
                    }
                } finally {
                    //判断是否是自己的锁
                    *//*Object u =redisTemplate.opsForValue().get(cacheLockKey);
                    if (uuid.equals(u)){
                        //如果是自己的 删除锁   删除不具备原子性
                        //解锁
                        redisTemplate.delete(cacheLockKey);
                    }*//*
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";

                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
                }
            }else {
                //未获取到锁 去获取缓存数据即可
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheLockKey);
            }
        }
        //统一返回
        return skuInfo;
    }*/
    //查库存信息 及库存的图片 条件库存Id
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;  //本次是查询SkuInfo的数据 拼接了 skuId
        //1:查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //2:有 直接返回
        if(skuInfo == null){
            //3:没有 查询DB
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //3.1:加锁
            RLock lock = redissonClient.getLock(cacheLockKey);
            //过期不候的锁
            //参数1： 过期不候的过期是多长时间
            //参数2： 获取到锁之后 锁的过期时间
            //参数3： 单位
            try {
                boolean isLock = lock.tryLock(1, 1, TimeUnit.SECONDS);
                if(isLock){
                    //获取到了锁
                    //库存信息
                    try {
                        skuInfo = skuInfoMapper.selectById(skuId);
                        if(null != skuInfo){
                            //库存的图片
                            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                    .eq("sku_id", skuId));
                            skuInfo.setSkuImageList(skuImageList);
                            //4:再保存一份到缓存中
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), //解决缓存雪崩
                                    TimeUnit.SECONDS);//过期时间一天+随机数（5分钟之内）
                        }else{
                            //代码能执行在此处  说明DB中也没有数据
                            //缓存的穿透问题  不让访问把DB弄挂掉
                            //将空结果保存到缓存中
                            skuInfo = new SkuInfo();// 不是NULL 是空结果  结果是skuInfo对象 对象中没有数据 叫空结果
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);//过期时间是5分钟
                        }
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                }else{
                    //未获取到锁  去获取缓存数据即可
                    try {
                        TimeUnit.SECONDS.sleep(1);//1S   时间差
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //5：统一返回
        return skuInfo;
    }
    //2.上面有一二三级分类
    @Override
    @Transactional//事物注解
    @GmallCache(prefix="getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }
    //要求价格单独查询 从MySql中查询
    @Override
    public BigDecimal getPrice(Long skuId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",skuId);
        queryWrapper.select("price");//默认所有字段
        SkuInfo skuInfo = skuInfoMapper.selectOne(queryWrapper);
        if (skuInfo != null){
            return skuInfo.getPrice();
        }
        return null;
    }
    //查询销售属性及属性值并选中
    @Override
    @GmallCache(prefix = "selectSpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> selectSpuSaleAttrListCheckBySku(Long spuId, Long skuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(spuId,skuId);
    }


    //5.组合查询
    @Override
    @GmallCache(prefix = "getSaleAttrValuesBySpu")
    public Map getSaleAttrValuesBySpu(Long spuId) {
        List<Map> listMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map result = new HashMap();
        listMap.forEach(map -> {
            result.put(map.get("value_ids"),map.get("sku_id"));
        });

        return result;
    }

    //6.查询分类视图中所有的分类数据
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }
    //7.根据品牌ID 查询品牌集合
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }
    //8.skuInfo 与平台属性及值的关联数据
    @Override
    public List<SkuAttrValue> getSkuAttrValueList(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValueList(skuId);
    }


}
